package com.ssh.pac;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class StorageForReentrantLock implements Storage{

	private Lock lock = new ReentrantLock();
	Condition full = lock.newCondition();
	Condition empty = lock.newCondition();
	
	
	@Override
	public void produce(int number) {
		lock.lock();
		try {
			if (list.size() + number > MAX_NUM) {
				System.out.println("仓库已满，无法生产产品");
				try {
					full.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int i= 0; i < number; i++) {
				list.add(new Product(i, Thread.currentThread().getName()+"i"));
			}
			System.out.println("已经生产了"+number+"件产品,仓库中共"+list.size()+"件产品");
			empty.signal();
		} finally {
			lock.unlock();
		}
	}

	@Override
	public void buy(int number) {
		lock.lock();
		try {
			if (list.size() - number < 0) {
				System.out.println("仓库库存不足，无法消费");
				try {
					empty.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int i= 0; i < number; i++) {
				list.remove();
			}
			System.out.println("已经消费了"+number+"件产品，仓库中还有"+list.size()+"件产品");
			full.signal();
		} finally {
			lock.unlock();
		}
	}

}
